from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def distributeCoins(self, root: Optional[TreeNode]) -> int:
        ans = 0
        def f(node):
            if node is None:
                return 0
            s = sum([f(node.left),f(node.right),node.val,-1])
            nonlocal ans
            ans += abs(s)
            return s
        f(root)
        return ans